package org.jeecg.modules.basedata.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.SsoUtil;
import org.jeecg.common.util.StringUtils;
import org.jeecg.entity.basedata.*;
import org.jeecg.enums.base.BaseCustomerCategoryEnum;
import org.jeecg.enums.base.BaseRoomStatusEnum;
import org.jeecg.modules.basedata.service.*;
import org.jeecg.modules.system.model.SysDepartTreeModel;
import org.jeecg.vo.basedata.BaseCustomerExcel;
import org.jeecg.vo.basedata.BaseCustomerPage;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;

/**
 * @Description: 业主
 * @Author: jeecg-boot
 * @Date:   2019-07-18
 * @Version: V1.0
 */
@Slf4j
@Api(tags="业主管理")
@RestController
@RequestMapping("/b/basedata/baseCustomer")
public class BaseCustomerController {
	@Autowired
	private IBaseCustomerService baseCustomerService;
	@Autowired
	private IBaseRoomService baseRoomService;
	@Autowired
	private IBaseProjectService baseProjectService;
	@Autowired
	private IBaseFloorService baseFloorService;

	@GetMapping("/getCustomerAndTenant")
	public Result getCustomerAndTenant(@RequestParam(name = "type", required = true) String type,
									 @RequestParam(name = "floorId", required = true) String floorId){
		Result result = new Result();
		try {
			List<SysDepartTreeModel> roomList = null;
			if("1".equals(type)){//租户
				roomList =  baseProjectService.queryTenantList(floorId);
			}
			if("2".equals(type)){//业主
				roomList =  baseProjectService.queryCustomerList(floorId);
			}
			result.setResult(roomList);
		}catch (Exception e){
			log.error(e.getMessage(),e);
   		    result.error500("操作失败");
		}
		return result;
	}

	/**
	  * 分页列表查询
	 * @param baseCustomer
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	@AutoLog(value = "业主-分页列表查询")
	@ApiOperation(value="业主-分页列表查询", notes="业主-分页列表查询")
	@GetMapping(value = "/list")
	public Result<IPage<BaseCustomerPage>> queryPageList(BaseCustomerPage baseCustomer,
									  @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
									  @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
									  HttpServletRequest req) {
		Result<IPage<BaseCustomerPage>> result = new Result<IPage<BaseCustomerPage>>();
		try{
			Page<BaseCustomerPage> pageList = new Page<BaseCustomerPage>(pageNo, pageSize);
			pageList = baseCustomerService.listByParams(pageList,baseCustomer);
			result.setSuccess(true);
			result.setResult(pageList);
		} catch (Exception e) {
			log.error(e.getMessage(),e);
			result.error500("操作失败");
		}

		return result;
	}

	/**
	  *   添加
	 * @param baseCustomer
	 * @return
	 */
	@AutoLog(value = "业主-添加")
	@ApiOperation(value="业主-添加", notes="业主-添加")
	@PostMapping(value = "/add")
	public Result<BaseCustomer> add(@RequestBody BaseCustomer baseCustomer) {
		String upRoomStatus = BaseRoomStatusEnum.BASE_ROOM_STATUS_CHECKIN.getCode()+"";//迁入房间状态
		baseCustomer.setExplainyy("新进户");
		String upRoomId = baseCustomer.getRoomId();
//		try {
			int count = baseCustomerService.getCountByRoomIdAndCustomerName(baseCustomer.getRoomId(),baseCustomer.getName().trim());
			if (count > 0){
				return Result.error("当前房间已有("+ baseCustomer.getName() +")住户，请勿重复添加");
			}
			if (BaseCustomerCategoryEnum.BASE_CUSTOMER_CATEGORY_OWNER.getCode() == Integer.parseInt(baseCustomer.getCustomerCategory())){
				int customerCount =  baseCustomerService.getCountByRoomId(baseCustomer.getRoomId());
				if (customerCount > 0){
					return Result.error("当前房间下已经有业主，请勿重复添加");
				}
				//只有当迁入的为业主才改变房间状态
				baseRoomService.updateRoomStatus(upRoomId,upRoomStatus);
			}
			baseCustomerService.save(baseCustomer);
			return Result.ok("添加成功！");
//		} catch (Exception e) {
//			log.error(e.getMessage(),e);
//			result.error500("操作失败");
//		}
//		return result;
	}
	
	/**
	  *  编辑
	 * @param baseCustomer
	 * @return
	 */
	@AutoLog(value = "业主-编辑")
	@ApiOperation(value="业主-编辑", notes="业主-编辑")
	@PutMapping(value = "/edit")
	public Result<BaseCustomer> edit(@RequestBody BaseCustomer baseCustomer) {
		String upRoomId = baseCustomer.getRoomId();
		//String upRoomStatus = baseCustomer.getRoomStatus();
		Result<BaseCustomer> result = new Result<BaseCustomer>();
		BaseCustomer baseCustomerEntity = baseCustomerService.getById(baseCustomer.getId());
		if(baseCustomerEntity==null) {
			result.error500("未找到对应实体");
		}else {
			boolean ok = baseCustomerService.updateById(baseCustomer);
			//TODO 返回false说明什么？
			if(ok) {
				result.success("修改成功!");
			}
		}
		return result;
	}
	
	/**
	  *   通过id删除
	 * @param id
	 * @return
	 */
	@AutoLog(value = "业主-通过id删除")
	@ApiOperation(value="业主-通过id删除", notes="业主-通过id删除")
	@DeleteMapping(value = "/delete")
	public Result<?> delete(@RequestParam(name="id",required=true) String id) {
		try {
			baseCustomerService.removeById(id);
		} catch (Exception e) {
			log.error("删除失败",e.getMessage());
			return Result.error("删除失败!");
		}
		return Result.ok("删除成功!");
	}
	
	/**
	  *  批量删除
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "业主-批量删除")
	@ApiOperation(value="业主-批量删除", notes="业主-批量删除")
	@DeleteMapping(value = "/deleteBatch")
	public Result<BaseCustomer> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		Result<BaseCustomer> result = new Result<BaseCustomer>();
		if(ids==null || "".equals(ids.trim())) {
			result.error500("参数不识别！");
		}else {
			this.baseCustomerService.removeByIds(Arrays.asList(ids.split(",")));
			result.success("删除成功!");
		}
		return result;
	}
	
	/**
	  * 通过id查询
	 * @param id
	 * @return
	 */
	@AutoLog(value = "业主-通过id查询")
	@ApiOperation(value="业主-通过id查询", notes="业主-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<BaseCustomer> queryById(@RequestParam(name="id",required=true) String id) {
		Result<BaseCustomer> result = new Result<BaseCustomer>();
		BaseCustomer baseCustomer = baseCustomerService.getById(id);
		if(baseCustomer==null) {
			result.error500("未找到对应实体");
		}else {
			result.setResult(baseCustomer);
			result.setSuccess(true);
		}
		return result;
	}


	@GetMapping(value = "/detailById")
	public Result<BaseCustomer> detailById(@RequestParam(name="id",required=true) String id,
										   @RequestParam(name="methodId",required=true) String methodId) {
		Result<BaseCustomer> result = new Result<BaseCustomer>();
		BaseCustomer baseCustomer = baseCustomerService.detailById(id, methodId);
		if(baseCustomer==null) {
			result.error500("未找到对应实体");
		}else {
			result.setResult(baseCustomer);
			result.setSuccess(true);
		}
		return result;
	}

	 /**
	  * 通过房间id查询
	  * @param
	  * @return
	  */
	 @AutoLog(value = "业主-通过房间id查询")
	 @ApiOperation(value="业主-通过房间id查询", notes="业主-通过房间id查询")
	 @GetMapping(value = "/queryByRoomId")
	 public Result<BaseCustomer> queryByRoomId(@RequestParam(name="roomid") String roomid) {
		 BaseCustomer baseCustomer = baseCustomerService.queryByRoomId(roomid);
		 if(baseCustomer==null) return Result.error("未找到业主");
		 return Result.ok(baseCustomer);
	 }

	 /**
	  * 通过roomId查询该房间是否有客人入住
	  * @param roomid
	  * @return
	  */
	 @AutoLog(value = "业主-通过id查询")
	 @ApiOperation(value="业主-通过id查询", notes="业主-通过id查询")
	 @GetMapping(value = "/listCustomerId")
	 public Result<String> listCustomerId(@RequestParam(name="roomid",required=true) String roomid) {
		 Result<String> result = new Result<>();
		 Integer  countCustomer = baseCustomerService.listCustomerId(roomid);

		 if(countCustomer!=0) {
			 result.setResult("300");//有人入住
			 result.setSuccess(true);
		 }else {
			 result.setResult("200");//无人入住
			 result.setSuccess(true);
		 }
		 return result;
	 }
	 /**
	  *  迁出编辑
	  * @param baseCustomer
	  * @return
	  */
	 @AutoLog(value = "迁出-编辑")
	 @ApiOperation(value="迁出-编辑", notes="迁出-编辑")
	 @PutMapping(value = "/outEdit")
	 public Result<BaseCustomer> outEdit(@RequestBody BaseCustomer baseCustomer) {
		 Result<BaseCustomer> result = new Result<BaseCustomer>();
		 BaseCustomer baseCustomers = baseCustomerService.getById(baseCustomer.getId());
		 baseCustomers.setDelFlag("1");
		 baseCustomers.setRemarks(baseCustomer.getRemarks());
		 baseCustomers.setEndDate(baseCustomer.getEndDate());
		 baseCustomers.setExplainyy("迁出");
		 baseCustomers.setUpdateTime(new Date());
		 baseCustomers.setUpdateBy(SsoUtil.getLoginUser().getId());
		 try {
		 	//当迁出为业主时  改变房间状态
		 	if (BaseCustomerCategoryEnum.BASE_CUSTOMER_CATEGORY_OWNER.getCode().equals(Integer.parseInt(baseCustomers.getCustomerCategory()))){
				baseRoomService.syupdateRoomStatus(baseCustomers.getRoomId());
			}
			 boolean ok = baseCustomerService.updateById(baseCustomers);
		  	 result.success("修改成功!");
		 } catch (Exception e) {
			 log.error(e.getMessage(),e);
			 result.error500("修改失败");
		 }
		 return result;
	 }

	 /**
	  * 历史记录列表查询
	  * @param baseCustomer
	  * @param pageNo
	  * @param pageSize
	  * @param req
	  * @return
	  */
	 @AutoLog(value = "历史记录-分页列表查询")
	 @ApiOperation(value="历史记录-分页列表查询", notes="历史记录-分页列表查询")
	 @GetMapping(value = "/listHistory")
	 public Result<IPage<BaseCustomerPage>> listHistory(BaseCustomer baseCustomer,
														  @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
														  @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
														  HttpServletRequest req) {
		 Result<IPage<BaseCustomerPage>> result = new Result<IPage<BaseCustomerPage>>();
		 try{
		 	if (StringUtils.isBlank(baseCustomer.getId())){
		 		return Result.error("查询参数有误！");
			}
		 	//id中包含basecustomer 代表为basecustomer表id，否则代表的是room表id
		 	if (baseCustomer.getId().contains("basecustomer")){
		 		BaseCustomer customer = baseCustomerService.getById(baseCustomer.getId().replace("basecustomer",""));
		 		baseCustomer.setRoomId(customer.getRoomId());
			}else {
		 		baseCustomer.setRoomId(baseCustomer.getId().replace("baseroom",""));
			}
			 Page<BaseCustomerPage> page = new Page<BaseCustomerPage>(pageNo, pageSize);
			 IPage<BaseCustomerPage> pageList = baseCustomerService.listHistory(page, baseCustomer);
			 result.setSuccess(true);
			 result.setResult(pageList);
		 } catch (Exception e) {
			 log.error(e.getMessage(),e);
			 result.error500("操作失败");
		 }
		 return result;
	 }


  /**
      * 导出excel
   *
   * @param request
   * @param response
   */
  @RequestMapping(value = "/exportXls")
  public ModelAndView exportXls(HttpServletRequest request, HttpServletResponse response, BaseCustomerPage baseCustomer) {
	  LoginUser user = SsoUtil.getLoginUser();
	  Page<BaseCustomerPage> page = new Page<BaseCustomerPage>(1, baseFloorService.list().size());
      //Step.2 AutoPoi 导出Excel
      ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
      Page<BaseCustomerPage> pageList = baseCustomerService.listByParams(page, baseCustomer);
      List<BaseCustomerPage> list = new ArrayList<>();
	  for (BaseCustomerPage b : pageList.getRecords()) {
		  BaseCustomerPage vo = new BaseCustomerPage();
		  BeanUtils.copyProperties(b, vo);
		  list.add(vo);
	  }
      //导出文件名称
      mv.addObject(NormalExcelConstants.FILE_NAME, "业主列表");
      mv.addObject(NormalExcelConstants.CLASS, BaseCustomerPage.class);
      mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("业主列表数据", "导出人:" + user.getRealname(), "导出信息"));
      mv.addObject(NormalExcelConstants.DATA_LIST, list);
      return mv;
  }

  /**
      * 通过excel导入数据
   *
   * @param request
   * @param response
   * @return
   */
  @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
  public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
      MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
      Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
      for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
          MultipartFile file = entity.getValue();// 获取上传文件对象
          ImportParams params = new ImportParams();
		  int titleRow = 0;
          params.setTitleRows(titleRow);
          params.setHeadRows(titleRow);
          params.setNeedSave(true);
          try {
              List<BaseCustomerExcel> listBaseCustomers = ExcelImportUtil.importExcel(file.getInputStream(), BaseCustomerExcel.class, params);
			  if(listBaseCustomers.size() <= 0){
				  return Result.error("文件内容为空，导入失败!");
			  }
			  int failureNum = 0;
			  StringBuilder failureMsg = new StringBuilder();
			  //住户信息
			  List<BaseCustomer> baseCustomers = new ArrayList<>();
			  //房间信息
			  List<BaseRoom> baseRoomList = new ArrayList<>();
			  for (BaseCustomerExcel baseCustomerExcel: listBaseCustomers){
				  titleRow++;
				  if (StringUtils.isBlank(baseCustomerExcel.getProjectName())){
					  failureMsg.append("<br/>第").append(titleRow).append("行：请输入项目名称; ");
					  failureNum++;
					  continue;
				  }
				  BaseProject baseProject = baseProjectService.getProjectByName(baseCustomerExcel.getProjectName());
				  if (baseProject == null) {
					  failureMsg.append("<br/>第").append(titleRow).append("行：填写的项目名称系统中不存在; ");
					  failureNum++;
					  continue;
				  }
				  if (StringUtils.isBlank(baseCustomerExcel.getFloorName())){
					  failureMsg.append("<br/>第").append(titleRow).append("行：请输入楼宇名称; ");
					  failureNum++;
					  continue;
				  }
				  BaseFloor baseFloor = baseFloorService.queryFloorName(baseProject.getId(), baseCustomerExcel.getFloorName());
				  if (baseFloor == null){
					  failureMsg.append("<br/>第").append(titleRow).append("行：填写的楼宇名称系统中不存在; ");
					  failureNum++;
					  continue;
				  }
				  if (StringUtils.isBlank(baseCustomerExcel.getRoomName())){
					  failureMsg.append("<br/>第").append(titleRow).append("行：请输入房间名称; ");
					  failureNum++;
					  continue;
				  }
				  while (baseCustomerExcel.getRoomName().endsWith(".0")){
					  baseCustomerExcel.setRoomName(baseCustomerExcel.getRoomName().substring(0,baseCustomerExcel.getRoomName().length() - 2 ));
				  }
				  BaseRoom baseRoom = baseRoomService.getBaseRoomByName(baseCustomerExcel.getRoomName(), baseFloor.getId());
				  if ( baseRoom == null){
					  failureMsg.append("<br/>第").append(titleRow).append("行：填写的房间名称系统中不存在; ");
					  failureNum++;
					  continue;
				  }
				  if (baseCustomerExcel.getCustomerCategory() == null){
					  failureMsg.append("<br/>第").append(titleRow).append("行：请选择住户类型; ");
					  failureNum++;
					  continue;
				  }
				  if (StringUtils.isBlank(baseCustomerExcel.getName()) && baseCustomerExcel.getName().trim().length() <= 0){
					  failureMsg.append("<br/>第").append(titleRow).append("行：请输入住户姓名; ");
					  failureNum++;
					  continue;
				  }
				  /*if (baseCustomerExcel.getChargeTime() == null){
					  failureMsg.append("<br/>第").append(titleRow).append("行：请输入开始收费时间; ");
					  failureNum++;
					  continue;
				  }*/
				  baseCustomerExcel.setName(baseCustomerExcel.getName().trim());

				  //判断房间下 业主是否已经存在
				  if (baseCustomerExcel.getCustomerCategory().equals(BaseCustomerCategoryEnum.BASE_CUSTOMER_CATEGORY_OWNER.getCode())){
					  int customerCount =  baseCustomerService.getCountByRoomId(baseRoom.getId());
					  if (customerCount > 0){
						  failureMsg.append("<br/>第").append(titleRow).append("行：["+baseRoom.getName()+"]房间已有业主，不能重复添加业主;");
						  failureNum++;
						  continue;
					  }else {
					  	baseRoom.setRoomStatus(BaseRoomStatusEnum.BASE_ROOM_STATUS_CHECKIN.getCode());
					  	baseRoomList.add(baseRoom);
					  }
				  }
				  if (StringUtils.isNotBlank(baseCustomerExcel.getMobile())){
					  while (baseCustomerExcel.getMobile().endsWith(".0")){
						  baseCustomerExcel.setMobile(baseCustomerExcel.getMobile().substring(0, baseCustomerExcel.getMobile().length() - 2));
					  }
				  }
				  if (StringUtils.isNotBlank(baseCustomerExcel.getIdcard())){
					  while (baseCustomerExcel.getIdcard().endsWith(".0")){
						  baseCustomerExcel.setIdcard(baseCustomerExcel.getIdcard().substring(0, baseCustomerExcel.getIdcard().length() - 2));
					  }
				  }
				  baseCustomerExcel.setProjectId(baseProject.getId());
				  baseCustomerExcel.setFloorId(baseFloor.getId());
				  BaseCustomer baseCustomer = new BaseCustomer();
				  BeanUtils.copyProperties(baseCustomerExcel, baseCustomer);
				  baseCustomer.setCustomerCategory(baseCustomerExcel.getCustomerCategory()+"");
				  baseCustomer.setRoomId(baseRoom.getId());
				  baseCustomer.setCustomerType("个人");
				  baseCustomers.add(baseCustomer);
			  }
			  if (failureNum > 0){
				  return Result.error("文件导入失败:" + failureMsg.toString());
			  }
              baseCustomerService.addBatchCustomer(baseCustomers,baseRoomList);
              return Result.ok("文件导入成功！数据行数:" + listBaseCustomers.size());
          } catch (Exception e) {
              log.error(e.getMessage(),e);
              return Result.error("文件导入失败:"+e.getMessage());
          } finally {
              try {
                  file.getInputStream().close();
              } catch (IOException e) {
                  e.printStackTrace();
              }
          }
      }
      return Result.ok("文件导入失败！");
  }

}
